package com.xh.bussiness.tiku.controller;

import com.xh.bussiness.jingyou.service.IJYQuestionService;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.bean.request.*;
import com.xh.bussiness.tiku.constant.TikuEsContant;
import com.xh.bussiness.tiku.model.Question;
import com.xh.bussiness.tiku.model.QuestionImportLog;
import com.xh.bussiness.tiku.model.QuestionTypeRelation;
import com.xh.bussiness.tiku.service.IQuestionChapterKnowledgeService;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.bussiness.tiku.service.IQuestionTypeRelationService;
import com.xh.bussiness.tiku.util.QuestionUtils;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.service.IElasticSearchService;
import com.xh.core.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 * @Author daiwei
 * @Description
 * @Date 2019/2/27 11:03
 **/
@Api(tags = "题库-试题接口")
@RestController
@RequestMapping("/tiku/question")
public class QuestionController extends BaseController {

    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IJYQuestionService jyquestionService;
    @Autowired
    private IQuestionTypeRelationService questionTypeRelationService;
    @Autowired
    private IElasticSearchService elasticSearchService;
    @Autowired
    private IQuestionChapterKnowledgeService questionChapterKnowledgeService;

    @PostMapping("/add")
    @ApiOperation(value = "试题新增", notes = "试题新增")
    @Transactional
    public AjaxResult add(@RequestBody QuestionSaveRequest bean) {
        //来源：1自建：2：word导入
        bean.setFrom(1);
        QuestionDto question = questionService.addQuestion(bean);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, question);
    }

    @PostMapping("/batchSaveQuestion")
    @ApiOperation(value = "批量保存试题", notes = "批量保存试题")
    @Transactional
    public AjaxResult batchSaveQuestion(@RequestBody BatchSaveQuestionRequest request) {
        String msg = questionService.batchSaveQuestion(request);
        return new AjaxResult(StringUtils.isEmpty(msg), StringUtils.isEmpty(msg) ? "保存成功" : msg);
    }

    @PostMapping("/modify")
    @ApiOperation(value = "试题修改", notes = "试题修改")
    @Transactional
    public AjaxResult modify(@RequestBody QuestionSaveRequest bean) {
        String msg = questionService.modifyQuestion(bean);
        return new AjaxResult(msg == null, msg);
    }

    @PostMapping("/editQuestion")
    @ApiOperation(value = "试题修改", notes = "试题修改")
    @Transactional
    public AjaxResult editQuestion(@RequestBody QuestionSaveRequest bean) {

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionService.editQuestion(bean));
    }

    @PostMapping("/editOptionArrangements")
    @ApiOperation(value = "试题答案排列方式修改", notes = "试题答案排列方式修改")
    public AjaxResult editQuestionOptionArrangements(@RequestBody Question question){
        Boolean flag = questionService.editQuestionOptionArrangements(question);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "试题删除", notes = "试题删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试题ID", required = true, dataType = "String"),
    })
    @Transactional
    public AjaxResult delete(String id) {
        String msg = questionService.deleteQuestion(id);
        return new AjaxResult(msg == null, msg);
    }

    @PostMapping("/queryPage")
    @ApiOperation(value = "试题分页查询", notes = "试题分页查询")
    public AjaxResult queryPage(@RequestBody QuestionQueryRequest bean) throws Exception {
        XhPage page = new XhPage();
        page.setCurrent(bean.getCurrent());
        page.setSize(bean.getSize());

        if (bean.getSearchType() == 2) {
            if ((bean.getKnowledgePoints() == null || bean.getKnowledgePoints().isEmpty()) && bean.getDataType().equals(1)) {
                return new AjaxResult(AjaxResultConstant.Result.ERROR, "按知识点查询时，知识点不能为空");
            }
        } else {
           /* if (bean.getBookVersionId() == null || bean.getBookVersionId().trim() == "") {
                return new AjaxResult(AjaxResultConstant.Result.ERROR, "按章节查询时，一级目录不能为空");
            }*/
            // bean.setKnowledgePoints(null);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", questionService.queryQuestionPage(page, bean));
    }

    @PostMapping("/getQuestion")
    @ApiOperation(value = "单题试题查询", notes = "试题查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "学科", required = false, dataType = "String"),
            @ApiImplicitParam(name = "id", value = "试题ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "version", value = "试题版本", required = false, dataType = "Integer"),
    })
    public AjaxResult getQuestion(String subject, String id, Integer version) throws Exception {
        if (StringUtils.isEmpty(id)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "试题id不能为空");
        }
        QuestionDto question = null;
        if (StringUtils.isEmpty(subject)) {
            question = questionService.getQuestion(id, version, true,true,true,true,true);
        } else {
            question = jyquestionService.queryAnalyze(subject, id);
        }

        if (question == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "未找到此id试题");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", question);
    }


    @PostMapping("/query")
    @ApiOperation(value = "试题查询", notes = "试题查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "试题信息", required = true, dataType = "QuestionQueryRequest"),
    })
    public AjaxResult query(QuestionQueryRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", questionService.queryQuestion(bean));
    }

    @PostMapping("/queryRandom")
    @ApiOperation(value = "试题随机查询", notes = "试题随机查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "试题信息", required = true, dataType = "QuestionQueryRequest"),
    })
    public AjaxResult queryRandom(QuestionQueryRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", questionService.queryQuesitonRandom(bean));
    }

    @PostMapping("/importWordQuestions")
    @ApiOperation(value = "Word试题导入", notes = "Word试题导入,返回解析信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subjectId", value = "学科id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "subjectName", value = "学科名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "path", value = "Word试题路径", required = true, dataType = "String"),
            @ApiImplicitParam(name = "fileName", value = "文件名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "schoolId", value = "龙文校区id", required = true, dataType = "Integer"),
    })
    public AjaxResult importWordQuestions(String subjectId, String subjectName, String path, String fileName, Integer schoolId, HttpServletRequest request) {
        QuestionImportLog questionImportLog = questionService.importQuestion(subjectId, subjectName, path, fileName, schoolId, request);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", questionImportLog);
    }

    @PostMapping("/convertLatexText2Html")
    @ApiOperation(value = "转换latex文本为Html", notes = "转换latex文本为Html")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "text", value = "latex文本", required = true, dataType = "String"),
    })
    public AjaxResult convertLatexText2Image(String text, HttpServletRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", QuestionUtils.convertLatexText2Html(text));
    }


    @PostMapping("/initQuestionData")
    public AjaxResult initQuestionData() {
        questionService.downloadQuestionDataRes();
        //questionService.initQuestionData();
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @PostMapping("/queryByIds")
    @ResponseBody
    public AjaxResult queryByIds(@RequestBody QueryQuestionRequest request) throws Exception {
        if (StringUtils.isEmpty(request.getSubject()) || CollectionUtils.isEmpty(request.getIds())) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionService.queryFromJY(request.getSubject(), request.getIds()));
    }

    @PostMapping("/queryQuestionByIds")
    @ResponseBody
    public AjaxResult queryQuestionByIds(@RequestBody QuestionQueryRequest bean) throws Exception {
        if (bean.getIds().length == 0) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionService.queryQuestion(bean));
    }

    /**
     * 根据图片搜索试题
     *
     * @param imgPath
     * @return
     * @throws Exception
     */
    @PostMapping("/queryByImg")
    public AjaxResult queryByImg(HttpServletRequest request, String imgPath) throws Exception {
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, jyquestionService.queryByImg(rootPath + imgPath));
    }

    /**
     * 查询相似题
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询相似题")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, dataType = "String"),
    })
    @PostMapping("/querySimilar")
    public AjaxResult querySimilar(XhPage page, QuestionQueryRequest bean) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionService.querySimilar(page, bean));
    }

    @ApiOperation(value = "菁优网查询相似题")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "学科", required = true, dataType = "String"),
            @ApiImplicitParam(name = "id", value = "题目id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "count", value = "查询数量", required = true, dataType = "int"),
    })
    @PostMapping("/queryJYSimilar")
    public AjaxResult querySimilar(String subject, String id, @RequestParam(defaultValue = "5") Integer count) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, jyquestionService.queryRecommond(subject, id, count));
    }

    @ApiOperation(value = "查询题目解析")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "学科", required = true, dataType = "String"),
            @ApiImplicitParam(name = "id", value = "题目id", required = true, dataType = "String"),
    })
    @PostMapping("/queryAnalyze")
    public AjaxResult queryAnalyze(String subject, String id) throws Exception {
        QuestionDto dto;
        if (StringUtils.isEmpty(subject)) {
            dto = questionService.getQuestion(id, null);
        } else {
            dto = jyquestionService.queryAnalyze(subject, id);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, dto);
    }

    /**
     * 查询变试题
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询变试题")
    @PostMapping("/queryVariant")
    public AjaxResult queryVariant(@RequestBody List<QuestionVariantRequest> beans) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionService.queryVariant(beans));
    }

    /**
     * 查询变试题
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "搜索试题")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "学科", required = false, dataType = "String"),
            @ApiImplicitParam(name = "value", value = "搜索关键字", required = true, dataType = "String"),
            @ApiImplicitParam(name = "current", value = "页码", required = false, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, dataType = "int"),
    })
    @PostMapping("/queryByKey")
    public AjaxResult queryByKey(String subject, String value, XhPage<QuestionDto> page) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, jyquestionService.queryByKey(subject, value, page));
    }


    @ApiOperation(value = "根据学科查询试题类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "学科", required = true, dataType = "String"),
    })
    @RequestMapping("/queryQuestionTypeBySubject")
    public AjaxResult queryQuestionTypeBySubject(String subject) {
        List<QuestionTypeRelation> questionTypeRelations = questionTypeRelationService.queryBySubject(subject);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionTypeRelations);
    }


    @ApiOperation(value = "查询试题类型总数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "学科", required = true, dataType = "String"),
    })
    @PostMapping("/getQuestionCountByType")
    public AjaxResult getQuestionCountByType(@RequestBody QuestionQueryRequest bean) {

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionService.getQuestionByType(bean));
    }

    @ApiOperation(value = "查询基础试题类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "学科", required = true, dataType = "String"),
    })
    @PostMapping("/queryBaticTypeBySubject")
    public AjaxResult queryBaticTypeBySubject(String subject) {
        if (StringUtils.isEmpty(subject)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionTypeRelationService.queryBaticTypeBySubject(subject));
    }


    @RequestMapping("/reflash")
    public void reflash() {
        questionTypeRelationService.reflash();
    }

    @PostMapping("/querySimilarQuestions")
    public AjaxResult querySimilarQuestions(@RequestBody QuerySimilarQuestionsRequest request) {
        if (CollectionUtils.isEmpty(request.getRepeatInfos())) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, questionService.querySimilarQuestions(request.getRepeatInfos()));
    }


    //es搜索相似题
    @RequestMapping("/matchQueryPercent")
    public AjaxResult matchQueryPercent(String subjectId, String text, String percent) {
        Map matchQueryPercent = elasticSearchService.matchQueryPercent("subjectId", subjectId, "title", text, percent + "%", TikuEsContant.ES_INDEX_TIKU,
                TikuEsContant.TYPE.ES_INDEX_TYPE_QUESTION);
        Object hits = matchQueryPercent.get("hits");
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, hits);
    }

    @ExcludeLoginTokenIntercept
    @RequestMapping("/initQuestionChapterKnowledge")
    public AjaxResult initQuestionChapterKnowledge() {
        questionChapterKnowledgeService.initQuestionChapterKnowledge();
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }
}
